const express = require('express')
const router = express.Router()
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const userDb = require('../db/user-db')
const moment = require('moment')
const crypto = require('crypto')
const checkType = require('../utils/checkType')
const nodemailer = require('nodemailer');

router
    .post('/', async(req, res) => {
        let {body: {maddr}} = req
        logI("A-S", maddr, "send_email_verification_code", `${JSON.stringify(req.body)}`, "null")
        try {
            const error = checkType.sendEmailCode(req.body)
            if (error) {
                retError("send_email_verification_code",  maddr, 10001,  error.details[0].message, res);
            } else {
                let data = await userDb.mailExist(maddr);
                if(data){
                    let transporter = nodemailer.createTransport({
                        "host": process.env.ALIYUN_HOST,
                        "port": 465,
                        "secureConnection": true, // use SSL, the port is 465
                        "auth": {
                            "user": process.env.ALIYUN_USER, // user name
                            "pass": process.env.ALIYUN_PASS         // password
                        }
                    });
                    const code = crypto.randomInt(0, 1000000).toString().padStart(6, '0');
                    let mailOptions = {
                        from: 'no_reply@hsesmartinc.com', // sender address mailfrom must be same with the user
                        to: maddr, // list of receivers
                        subject: 'HSE WISE Verification Code', // Subject line
                        text: 'Hello world', // plaintext body
                        html: '<p>You have selected this email address as your HSE WISE account. To verify that this email address belongs to you, please enter the following verification code on the email verification page:</p><br>' +
                            '<h3>' + code + '</h3><br>' +
                            '<p>The verification code will expire five minutes after this email is sent.</p>' +
                            '<p>If you did not make this request, you can ignore this email. A HSE WISE Blue account can only be created after verification.</p><br>'// html body
                        , // html body
                        attachments: [],
                    };
                    const createTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    await userDb.updateCode(code,createTime,maddr);
                    transporter.sendMail(mailOptions, function(error, info){
                        if(error){
                            retError("send_email_verification_code",  maddr, 10005, error, res);
                        }else{
                            retSuccess("send_email_verification_code",  maddr, 0, "", res);
                        }
                    });
                }else{
                    retError("send_email_verification_code",  maddr, 10007, "user does not exist", res);
                }
            }
        } catch (e) {
            retError("send_email_verification_code",  maddr, 10001, e, res);
        }
    })

module.exports = router
